﻿using System;
using System.Linq;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using System.Diagnostics;
using Microsoft.Phone.Shell;
using System.Windows;

namespace VisualStudioAchievements
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            App.MainPageDispatcher = this.Dispatcher;
        }

        private void btnAddUser_Click(object sender, EventArgs e)
        {
            BindingPoint.Instance.HidePerfBar = true;
            NavigationService.Navigate(new Uri("/InputPage.xaml", UriKind.Relative));
        }

        private void StackPanel_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            foreach (Niner n in BindingPoint.Instance.Niners)
            {
                Debug.WriteLine(n.Alias);
            }

            //var unit = BindingPoint.Niners.First();
            var unit = (from c in BindingPoint.Instance.Niners where c.Alias == ((Grid)sender).Tag.ToString() select c).FirstOrDefault();
            Niner _nunit = (Niner)unit;

            BindingPoint.Instance.CurrentNiner = _nunit;
            NavigationService.Navigate(new Uri("/UserDetail.xaml", UriKind.Relative));
        }

        private void btnCompare_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/ComparePrompt.xaml", UriKind.Relative));
        }

        private void btnAbout_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AboutPage.xaml", UriKind.Relative));
        }

        private void mnuPin_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            string name = ((MenuItem)sender).Tag.ToString();
            Niner niner = (from c in BindingPoint.Instance.Niners where c.Alias == name select c).FirstOrDefault();

            Uri shellUri = new Uri("/UserDetail.xaml?niner=" + name, UriKind.Relative);
            ShellTile.Create(shellUri, new StandardTileData()
                {
                    Title = name,
                    BackgroundImage = niner.Avatar
                });
        }

        private void mnuDelete_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            string name = ((MenuItem)sender).Tag.ToString();
            if (MessageBox.Show("This will remove " + name + " from the list.", "Remove Niner", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                BindingPoint.Instance.Niners.Remove((from c in BindingPoint.Instance.Niners where c.Alias == name select c).FirstOrDefault());
                Util.SerializeNiners();
            }
        }
    }
}